<!-- 计划转生产委外 -->
<template>
  <pageHeader
    :title="title"
    :breadCrumb="['工厂建模', '生产BOM管理', title]"
    :show-back="true"
  >
    <template #buts>
      <a-button
        type="primary"
        @click="handleOk"
        v-if="type === 'add' || type === 'edit'"
        >提交</a-button
      >
    </template>
  </pageHeader>
  <div id="QecodeContent">
    <a-spin :loading="loading" class="cantainer">
      <!-- <div class="tab">基本信息</div> -->
      <TitleBox title="基本信息"></TitleBox>
      <a-form :model="form.list" ref="formRef" auto-label-width>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="委外订单号"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.number"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="物料编码"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.managementNumber"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="物料名称"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.materialName"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="产品规格"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.spec"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="本次委外数量"
              label-col-flex="100px"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                disabled
                placeholder="please enter..."
                v-model="form.list.amount"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="关联任务单号"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.taskNumber"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="委外工序"
              label-col-flex="100px"
            >
              {{ form.list.processName }}
              <!-- <a-select
                v-model="form.list.processIds"
                multiple
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
                allow-clear
                disabled
                @change="selectProcessGroups"
              >
                <a-option
                  v-for="item in processGroup"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.sort }} \ {{ item.name }}</a-option
                >
              </a-select> -->
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              field="rate"
              label="供应商"
              label-col-flex="100px"
              required
            >
              <a-select
                v-model="form.list.supplierId"
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
                :disabled="type !== 'add' && type !== 'edit'"
              >
                <a-option
                  v-for="item in SupplierInfo"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货日期"
              label-col-flex="100px"
            >
              <a-date-picker
                style="width: 320px"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                :disabled="type !== 'add' && type !== 'edit'"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="form.list.entryDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="form.list.itemState === 1" :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货人姓名"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                :disabled="type !== 'add' && type !== 'edit'"
                v-model="form.list.consigneeName"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货人电话"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneePhone"
                :disabled="type !== 'add' && type !== 'edit'"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货地址"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneeAddress"
                :disabled="type !== 'add' && type !== 'edit'"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="加工费(含税)"
              label-col-flex="100px"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                :disabled="type !== 'add' && type !== 'edit'"
                placeholder="please enter..."
                v-model="form.list.unitPrice"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="含税合计"
              label-col-flex="100px"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                disabled
                placeholder="please enter..."
                v-model="form.list.totalPrice"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item :show-colon="true" label="税率" label-col-flex="100px">
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                :disabled="type !== 'add' && type !== 'edit'"
                placeholder="please enter..."
                v-model="form.list.rate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="委外日期"
              label-col-flex="100px"
            >
              <a-date-picker
                style="width: 330px; margin: 0 24px 24px 0"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                :disabled="type !== 'add' && type !== 'edit'"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="form.list.outsourcingDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- <div class="tab"
        ><a-space
          ><div>附加物料清单</div
          ><a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="form.list.itemState"
            disabled
            @change="EnableInventory"
          >
            <template #checked> ON </template>
            <template #unchecked> OFF </template>
          </a-switch></a-space
        >
      </div> -->

      <TitleBox title="附加物料清单">
        <template #buts
          ><a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="form.list.itemState"
            disabled
            @change="EnableInventory"
          >
            <template #checked> ON </template>
            <template #unchecked> OFF </template>
          </a-switch></template
        >
      </TitleBox>
      <a-divider />

      <a-table
        :stripe="true"
        :dordered="{
          headerCell: true,
        }"
        :data="form.list.item"
        :scroll="scroll"
        :pagination="false"
      >
        <template #columns>
          <a-table-column
            title="物料编码"
            :width="100"
            align="center"
            data-index="managementNumber"
          ></a-table-column>
          <a-table-column
            title="物料名称"
            :width="100"
            align="center"
            data-index="managementName"
          ></a-table-column>
          <a-table-column
            v-if="type === 'add'"
            title="换算率"
            :width="100"
            align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.dosage" /> </template
          ></a-table-column>
          <a-table-column title="规格型号" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.spec" /> </template
          ></a-table-column>
          <a-table-column
            title="空闲数量"
            v-if="type === 'add'"
            :width="100"
            align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.freeAmount" /> </template
          ></a-table-column>
          <a-table-column title="推荐委外数量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input-number
                :min="1"
                v-model="record.amount"
                disabled
              /> </template
          ></a-table-column>
        </template>
      </a-table>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, watchEffect } from 'vue';
  import {
    getOutsourcingSupplier,
    postOutsourcing,
    getOutsourcingOne,
    putOutsourcingOne,
  } from '@/api/produce-management/production-operation/index';
  import { GetProductProcessRoutePage } from '@/api/FactoryModeling';
  import { getBarcode, delarcode } from '@/api/barcode';
  import { getSupplierInfo } from '@/api/buy-management/supplier-management/supplier-primary-list/index';
  import { GetProducePlanPage } from '@/api/produce-management/OrderPlanning';
  import { Message } from '@arco-design/web-vue';
  import { useRoute, useRouter } from 'vue-router';
  import dayjs from 'dayjs';

  const modelVisible = ref(false);
  const processGroup = ref([]);
  const formRef = ref();
  let route = useRoute();
  let router = useRouter();
  let loading = ref(false);
  let type = route.query.type;
  let title = route.query.name;
  const form = reactive<any>({
    list: {
      name: '1',
      item: [],
      outsourcingType: 1, // 委外类型
      planAmount: 0,
      planId: null,
      amount: 0,
      state: 1,
    },
  });
  const SupplierInfo = ref([]);

  const materialData = ref([]);
  const newDosage = ref();
  const treeData = (data: any) => {
    data.children?.forEach((item: any) => {
      if (item.children) {
        newDosage.value = item.dosage;
        treeData(item);
      } else if (item.children === null) {
        item.dosage *= newDosage.value;
        form.list.item.push({ ...item });
      }
    });
    return form.list.item;
  };

  const planList = ref();
  const getPlanList = async () => {
    try {
      const res = await GetProducePlanPage({
        page: 1,
        size: -1,
        type: 2,
      });
      planList.value = res.content.filter((i) => i.materialAttribute === 2);
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getPlanList();

  const getPlanInfo = async (id: any) => {
    const newArr = planList.value.filter((item) => item.id === id);
    Object.assign(form.list, newArr[0]);
    form.list.planId = form.list.id;
    form.list.managementId = form.list.productId;
    form.list.state = 1;
    delete form.list.id;
    const SupplierRes = await getSupplierInfo({
      id: form.list.productId,
    });
    SupplierInfo.value = SupplierRes;
  };

  // const EnableInventory = async (e) => {
  //   try {
  //     if (e === 1) {
  //       if (!form.list.productId) {
  //         Message.warning('请选择关联计划单');
  //         form.list.itemState = 2;
  //         return;
  //       }
  //       let newArr: any = [];
  //       const res = await getOutsourcingSupplier({ id: form.list.productId });
  //       treeData(res);
  //       form.list.item.forEach((ele: any) => {
  //         const index = newArr.findIndex((i: any) => ele.bomName === i.bomName);
  //         if (index === -1) {
  //           newArr.push({ ...ele });
  //         } else {
  //           newArr[index].dosage += ele.dosage;
  //         }
  //       });
  //       form.list.item = newArr;
  //       form.list.item.forEach((item: any) => {
  //         delete item.id;
  //       });
  //       if (form.list.amount !== null) {
  //         form.list.item.forEach((item: any) => {
  //           item.amount = form.list.amount * Number(item.dosage);
  //         });
  //       }
  //     } else {
  //       form.list.item = [];
  //     }
  //   } catch (err: unknown) {
  //   }
  // };

  watchEffect(() => {
    if (form.list.unitPrice && form.list.amount) {
      form.list.totalPrice = form.list.unitPrice * form.list.amount;
    }
  });

  const changeAmount = () => {
    if (form.list.item && form.list.amount) {
      form.list.item.forEach((item: any) => {
        item.amount = form.list.amount * Number(item.dosage);
      });
    }
  };

  const handleOk = () => {
    formRef.value.validate(async (res: any) => {
      if (!res) {
        if (type === 'edit') {
          form.list.outsourcingDate = new Date(
            form.list.outsourcingDate
          ).toJSON();
          form.list.entryDate = new Date(form.list.entryDate).toJSON();
          form.list.processIds = form.list.processIds.join(',');
          await putOutsourcingOne({ ...form.list });
          router.push({ name: 'ProcessOutsourcing' });
        }
      }
    });
  };

  const getData = async (id?: number) => {
    try {
      const res = await getOutsourcingOne({ id });
      const SupplierRes = await getSupplierInfo({
        id: res.managementId,
      });

      // const msg = await GetProductProcessRoutePage({
      //   page: 1,
      //   size: -1,
      //   history: 1,
      //   productId: res.managementId,
      // });
      // processGroup.value = msg.content[0].groupData.filter(
      //   (i) => i.productionMethod === '委外'
      // );
      // processGroup.value.sort((a, b) => a.sort - b.sort);
      SupplierInfo.value = SupplierRes;

      form.list = {
        ...res,
        materialNumber: res.managementNumber,
        materialName: res.managementName,
        processIds: res.processIds.split(','),
      };
      form.list.processIds = form.list.processIds.map(Number);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  onMounted(() => {
    if (type !== 'add') {
      getData(Number(route.query.id));
    }
  });

  const generateBarCode = () => {
    modelVisible.value = true;
  };

  const bb = (index: number) => {
    let canvas1 = document.getElementById('QecodeContent');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    let a = document.createElement('a');
    a.href = canvas[index].toDataURL('img/png');
    a.download = '二维码';
    a.click();
    Message.error('下载中，请稍后...');
  };

  const delQrcode = async (id?: number) => {
    await delarcode({ id });
    getData();
  };

  const addBarcode = () => {
    getData(Number(route.query.id));
  };
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
  }
  .form {
    padding-left: 100px;
    padding-right: 100px;
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 20px;
    font-size: 20px;
  }
  .orderBox {
    padding-left: 50px;
    // padding: 0px;
  }
</style>
